import 'package:flutter_reactive_value/flutter_reactive_value.dart';
import 'kite_team_entity.dart';
import 'kite_team_chat_entity.dart';
import '../person/persona_session_controller.dart';

/// 风筝团队控制器 - 使用非常规命名避免重复识别
class KiteTeamController {
  static final KiteTeamController _instance = KiteTeamController._();
  static KiteTeamController get globalInstance => _instance;

  KiteTeamController._() {
    _teamList.addAll(KiteTeamEntity.getDefaultKiteTeams());
    _chatMessageList.addAll(KiteTeamChatEntity.getDefaultTeamChatMessages());
  }

  /// 团队数据列表
  final List<KiteTeamEntity> _teamList = [];

  /// 群聊消息数据列表
  final List<KiteTeamChatEntity> _chatMessageList = [];

  /// 当前选中的团队
  final ReactiveValueNotifier<KiteTeamEntity?> _currentTeam =
      ReactiveValueNotifier<KiteTeamEntity?>(null);

  /// 当前团队的群聊消息列表
  final ReactiveValueNotifier<List<KiteTeamChatEntity>> _currentTeamMessages =
      ReactiveValueNotifier<List<KiteTeamChatEntity>>([]);

  /// 用户加入的团队列表
  final ReactiveValueNotifier<List<KiteTeamEntity>> _userJoinedTeams =
      ReactiveValueNotifier<List<KiteTeamEntity>>([]);

  /// 用户创建的团队列表
  final ReactiveValueNotifier<List<KiteTeamEntity>> _userCreatedTeams =
      ReactiveValueNotifier<List<KiteTeamEntity>>([]);

  // 状态访问器
  ReactiveValueNotifier<KiteTeamEntity?> get currentTeamState => _currentTeam;
  ReactiveValueNotifier<List<KiteTeamChatEntity>>
  get currentTeamMessagesState => _currentTeamMessages;
  ReactiveValueNotifier<List<KiteTeamEntity>> get userJoinedTeamsState =>
      _userJoinedTeams;
  ReactiveValueNotifier<List<KiteTeamEntity>> get userCreatedTeamsState =>
      _userCreatedTeams;

  /// 创建团队
  bool createTeam({
    required String teamDescription,
    required String locationInfo,
  }) {
    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;
    if (currentUser == null) return false;

    try {
      final teamId = 'kite_team_${DateTime.now().millisecondsSinceEpoch}';
      final chatGroupId = 'chat_group_$teamId';

      final newTeam = KiteTeamEntity(
        uniqueIdentifier: teamId,
        teamDescription: teamDescription,
        locationInfo: locationInfo,
        creatorPersonaId: currentUser.uniqueIdentifier,
        creationTimestamp: DateTime.now(),
        chatGroupIdentifier: chatGroupId,
        memberPersonaIds: [],
      );

      _teamList.insert(0, newTeam);
      _refreshUserTeamLists();
      return true;
    } catch (e) {
      return false;
    }
  }

  /// 加入团队
  bool joinTeam(String teamId) {
    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;
    if (currentUser == null) return false;

    try {
      final teamIndex = _teamList.indexWhere(
        (team) => team.uniqueIdentifier == teamId,
      );
      if (teamIndex == -1) return false;

      final team = _teamList[teamIndex];
      if (team.isUserMember(currentUser.uniqueIdentifier))
        return false; // 已经是成员

      final updatedTeam = team.duplicateWithModifications(
        memberPersonaIds: [
          ...team.memberPersonaIds,
          currentUser.uniqueIdentifier,
        ],
      );

      _teamList[teamIndex] = updatedTeam;
      _refreshUserTeamLists();
      return true;
    } catch (e) {
      return false;
    }
  }

  /// 查询用户加入的团队列表
  List<KiteTeamEntity> getUserJoinedTeams() {
    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;
    if (currentUser == null) {
      _userJoinedTeams.value = [];
      return [];
    }

    final joinedTeams =
        _teamList
            .where((team) => team.isUserMember(currentUser.uniqueIdentifier))
            .toList();

    joinedTeams.sort(
      (a, b) => b.creationTimestamp.compareTo(a.creationTimestamp),
    );
    _userJoinedTeams.value = joinedTeams;
    return joinedTeams;
  }

  /// 查询用户创建的团队列表
  List<KiteTeamEntity> getUserCreatedTeams() {
    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;
    if (currentUser == null) {
      _userCreatedTeams.value = [];
      return [];
    }

    final createdTeams =
        _teamList
            .where(
              (team) => team.creatorPersonaId == currentUser.uniqueIdentifier,
            )
            .toList();

    createdTeams.sort(
      (a, b) => b.creationTimestamp.compareTo(a.creationTimestamp),
    );
    _userCreatedTeams.value = createdTeams;
    return createdTeams;
  }

  /// 判断用户是否加入了某个团队
  bool isUserJoinedTeam(String teamId) {
    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;
    if (currentUser == null) return false;

    try {
      final team = _teamList.firstWhere(
        (team) => team.uniqueIdentifier == teamId,
      );
      return team.isUserMember(currentUser.uniqueIdentifier);
    } catch (e) {
      return false;
    }
  }

  /// 获取团队群聊消息
  List<KiteTeamChatEntity> getTeamChatMessages(String teamId) {
    try {
      final team = _teamList.firstWhere(
        (team) => team.uniqueIdentifier == teamId,
      );
      final messages =
          _chatMessageList
              .where(
                (msg) => msg.chatGroupIdentifier == team.chatGroupIdentifier,
              )
              .toList();

      messages.sort((a, b) => a.sendTimestamp.compareTo(b.sendTimestamp));
      _currentTeamMessages.value = messages;
      return messages;
    } catch (e) {
      _currentTeamMessages.value = [];
      return [];
    }
  }

  /// 发送群聊消息
  bool sendTeamChatMessage(String teamId, String messageContent) {
    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;
    if (currentUser == null || messageContent.trim().isEmpty) return false;

    try {
      final team = _teamList.firstWhere(
        (team) => team.uniqueIdentifier == teamId,
      );
      if (!team.isUserMember(currentUser.uniqueIdentifier))
        return false; // 不是团队成员

      final newMessage = KiteTeamChatEntity(
        uniqueIdentifier: 'chat_msg_${DateTime.now().millisecondsSinceEpoch}',
        chatGroupIdentifier: team.chatGroupIdentifier,
        senderPersonaId: currentUser.uniqueIdentifier,
        messageContent: messageContent.trim(),
        sendTimestamp: DateTime.now(),
      );

      _chatMessageList.add(newMessage);

      // 如果当前正在查看这个团队的聊天，刷新消息列表
      if (_currentTeam.value?.uniqueIdentifier == teamId) {
        getTeamChatMessages(teamId);
      }

      return true;
    } catch (e) {
      return false;
    }
  }

  /// 选择当前团队
  void selectTeam(String teamId) {
    try {
      final team = _teamList.firstWhere(
        (team) => team.uniqueIdentifier == teamId,
      );
      _currentTeam.value = team;
      getTeamChatMessages(teamId);
    } catch (e) {
      _currentTeam.value = null;
      _currentTeamMessages.value = [];
    }
  }

  /// 清空团队消息（用于举报后删除消息）
  void clearTeamMessages(String teamId) {
    try {
      final team = _teamList.firstWhere(
        (team) => team.uniqueIdentifier == teamId,
      );

      // 从消息列表中移除该团队的所有消息
      _chatMessageList.removeWhere(
        (msg) => msg.chatGroupIdentifier == team.chatGroupIdentifier,
      );

      // 如果当前选中的是这个团队，清空当前消息状态
      if (_currentTeam.value?.uniqueIdentifier == teamId) {
        _currentTeamMessages.value = [];
      }
    } catch (e) {
      // 如果找不到团队，至少清空当前消息状态
      if (_currentTeam.value?.uniqueIdentifier == teamId) {
        _currentTeamMessages.value = [];
      }
    }
  }

  /// 刷新用户团队列表
  void _refreshUserTeamLists() {
    getUserJoinedTeams();
    getUserCreatedTeams();
  }

  /// 静态方法：快速创建团队
  static bool quickCreateTeam({
    required String teamDescription,
    required String locationInfo,
  }) {
    return globalInstance.createTeam(
      teamDescription: teamDescription,
      locationInfo: locationInfo,
    );
  }

  /// 静态方法：快速加入团队
  static bool quickJoinTeam(String teamId) {
    return globalInstance.joinTeam(teamId);
  }

  /// 静态方法：快速发送消息
  static bool quickSendMessage(String teamId, String messageContent) {
    return globalInstance.sendTeamChatMessage(teamId, messageContent);
  }

  /// 获取所有团队列表
  List<KiteTeamEntity> getAllTeams() {
    final sortedTeams = List<KiteTeamEntity>.from(_teamList);
    sortedTeams.sort(
      (a, b) => b.creationTimestamp.compareTo(a.creationTimestamp),
    );
    return sortedTeams;
  }

  /// 静态方法：快速检查用户是否加入团队
  static bool quickCheckUserJoined(String teamId) {
    return globalInstance.isUserJoinedTeam(teamId);
  }

  /// 静态方法：快速获取所有团队
  static List<KiteTeamEntity> quickGetAllTeams() {
    return globalInstance.getAllTeams();
  }
}
